<template>
  <div class="team-page">
    <!-- 统计卡片 -->
    <div class="team-stats-card">
      <div class="stats-row">
        <div class="stats-left">
          <div class="stats-label">{{ t("user-team_labaTim") }}</div>
          <div class="stats-label-sec">{{ t("user-team_ukuranTimValid") }}</div>
        </div>
        <div class="stats-right">
          <div class="stats-value">
            COP{{ formatNumber(teamStats.teamProfit) }}
          </div>
          <div class="stats-value">{{ teamStats.validTeamSize }}</div>
        </div>
      </div>
      <div class="divider"></div>
      <div class="stats-row deposit-row">
        <div class="deposit-item">
          <div class="deposit-value">
            COP{{ formatNumber(teamStats.totalDeposit) }}
          </div>
          <div class="deposit-label">
            {{ t("user-team_jumlahTotalDeposit") }}
          </div>
        </div>
        <div class="deposit-item">
          <div class="deposit-value">
            COP{{ formatNumber(teamStats.todayDeposit) }}
          </div>
          <div class="deposit-label">
            {{ t("user-team_jumlahDepositHariIni") }}
          </div>
        </div>
      </div>
    </div>

    <!-- 标签模块容器 -->
    <div class="tabs-container">
      <!-- 团队等级标签 -->
      <div class="team-level-tabs">
        <div
          class="level-tab"
          :class="{ active: activeLevel === 'B' }"
          @click="switchLevel('B')"
        >
          {{ t("user-team_timB") }}({{ teamCounts.B }})
          <div class="level-underline" v-if="activeLevel === 'B'"></div>
        </div>
        <div
          class="level-tab"
          :class="{ active: activeLevel === 'C' }"
          @click="switchLevel('C')"
        >
          {{ t("user-team_timC") }}({{ teamCounts.C }})
          <div class="level-underline" v-if="activeLevel === 'C'"></div>
        </div>
        <!-- <div
          class="level-tab"
          :class="{ active: activeLevel === 'D' }"
          @click="switchLevel('D')"
        >
          {{ t("user-team_timD") }}({{ teamCounts.D }})
          <div class="level-underline" v-if="activeLevel === 'D'"></div>
        </div> -->
        <div
          class="level-tab"
          :class="{ active: activeLevel === 'E' }"
          v-if="userInfo.minlevel >= 15"
          @click="switchLevel('E')"
        >
          {{ t("user-team_timE") }}({{ teamCounts.E }})
          <div class="level-underline" v-if="activeLevel === 'E'"></div>
        </div>
        <div
          class="level-tab"
          :class="{ active: activeLevel === 'F' }"
          v-if="userInfo.minlevel >= 15"
          @click="switchLevel('F')"
        >
          {{ t("user-team_timF") }}({{ teamCounts.F }})
          <div class="level-underline" v-if="activeLevel === 'F'"></div>
        </div>
        <div
          class="level-tab"
          :class="{ active: activeLevel === 'G' }"
          v-if="userInfo.minlevel >= 15"
          @click="switchLevel('G')"
        >
          {{ t("user-team_timG") }}({{ teamCounts.G }})
          <div class="level-underline" v-if="activeLevel === 'G'"></div>
        </div>
      </div>

      <!-- 状态标签 -->
      <div class="status-tabs">
        <div
          class="status-tab"
          :class="{ active: activeStatus === 'valid' }"
          @click="switchStatus('valid')"
        >
          {{ t("user-team_valid")
          }}{{ activeStatus == "valid" ? "(" + countTeam + ")" : "" }}
          <div class="tab-indicator" v-if="activeStatus === 'valid'"></div>
        </div>
        <div
          class="status-tab"
          :class="{ active: activeStatus === 'invalid' }"
          @click="switchStatus('invalid')"
        >
          {{ t("user-team_invalid")
          }}{{ activeStatus == "invalid" ? "(" + countTeam + ")" : "" }}
          <div class="tab-indicator" v-if="activeStatus === 'invalid'"></div>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="team-content">
      <!-- Valid标签内容 -->
      <div v-if="activeStatus === 'valid'">
        <div v-if="teamMembers.length === 0" class="empty-state">
          <NoData />
        </div>
        <div v-else class="member-list">
          <!-- 添加团队成员列表内容 -->
          <div
            class="valid-member-card"
            v-for="member in teamMembers"
            :key="member.member"
          >
            <div class="member-header">
              <div class="member-phone">
                {{ member.areacode }} {{ member.tel }}
              </div>
              <div class="member-date">{{ member.regTime }}</div>
            </div>
            <div class="member-info">
              <div class="info-row">
                <div class="info-label">
                  {{ t("user-team_jumlahTotalDeposit") }}
                </div>
                <div class="info-value">
                  COP{{ formatNumber(member.totalIn || "0") }}
                </div>
              </div>
              <div class="info-row">
                <div class="info-label">
                  {{ t("user-team_produkHargaMaksimal") }}
                </div>
                <div class="info-value">
                  COP{{ formatNumber(member.maxAmouont || "0") }}
                </div>
              </div>
              <div class="info-row">
                <div class="info-label">
                  {{ t("user-team_tanggalJatuhTempo") }}
                </div>
                <div class="info-value">{{ member.validTime || "-" }}</div>
              </div>
            </div>
          </div>

          <!-- 加载更多按钮 -->
          <div class="load-more-container" v-if="hasMore">
            <div class="load-more-btn" @click="loadMore" v-if="!loading">
              {{ t("user-team_muatLebihBanyak") }}
            </div>
            <div class="loading-indicator" v-else>
              <van-loading type="spinner" size="24px" color="#f6eade" />
              <span>{{ t("user-coupon_memuat") }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Invalid 标签内容 -->
      <div v-if="activeStatus === 'invalid'">
        <div v-if="invalidMembers.length === 0" class="empty-state">
          <NoData />
        </div>
        <div v-else class="invalid-members">
          <div
            class="invalid-member-card"
            v-for="member in invalidMembers"
            :key="member.phone"
          >
            <div class="member-header">
              <div class="member-phone">{{ member.phone }}</div>
              <div class="member-date">{{ member.date }}</div>
            </div>
            <div class="member-info">
              <div class="info-row">
                <div class="info-label">
                  {{ t("user-team_jumlahTotalDeposit") }}
                </div>
                <div class="info-value">{{ member.totalDeposit }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">
                  {{ t("user-team_produkHargaMaksimal") }}
                </div>
                <div class="info-value">{{ member.maxProductPrice }}</div>
              </div>
              <div class="info-row">
                <div class="info-label">
                  {{ t("user-team_tanggalJatuhTempo") }}
                </div>
                <div class="info-value">{{ member.expiryDate }}</div>
              </div>
            </div>
          </div>

          <!-- 加载更多按钮 (对无效成员列表) -->
          <div class="load-more-container" v-if="hasMore">
            <div class="load-more-btn" @click="loadMore" v-if="!loading">
              {{ t("user-team_muatLebihBanyak") }}
            </div>
            <div class="loading-indicator" v-else>
              <van-loading type="spinner" size="24px" color="#f6eade" />
              <span>{{ t("user-coupon_memuat") }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watchEffect } from "vue";
import { useRouter } from "vue-router";
import NoData from "@/components/NoData.vue";
import { getMyTeam, getMyTeamInfo } from "@/api/user";
import { showToast } from "vant";
import { formatNumber } from "@/utils/public";

// 初始化数据
const router = useRouter();
const activeLevel = ref("B");
const activeStatus = ref("valid");
const loading = ref(false);
const loadingStats = ref(false);
const countTeam = ref("0");
const teamStats = reactive({
  teamProfit: 0,
  validTeamSize: 0,
  totalDeposit: 0,
  todayDeposit: 0,
});
const teamMembers = ref([]);
const invalidMembers = ref([]);
const userInfo = ref(<any>{});
const currentPage = ref(1);
const pageSize = 10;
const hasMore = ref(true);
const teamCounts = reactive({
  B: 0,
  C: 0,
  D: 0,
  E: 0,
  F: 0,
  G: 0,
});
const { t } = useI18n();
// 获取团队统计数据
function getTeamStatistics() {
  if (loadingStats.value) return;

  loadingStats.value = true;

  getMyTeamInfo()
    .then((res: any) => {
      loadingStats.value = false;

      if (res.code === 200) {
        const data = res.data || {};

        // 更新团队统计数据
        teamStats.teamProfit = parseInt(data.teamTotalProfit || 0);
        teamStats.validTeamSize = parseInt(data.totalCount || 0);
        teamStats.totalDeposit = parseInt(data.teamTotalIn || 0);
        teamStats.todayDeposit = parseInt(data.teamTodayIn || 0);

        // 更新团队人数统计
        teamCounts.B = parseInt(data.team1 || 0);
        teamCounts.C = parseInt(data.team2 || 0);
        teamCounts.D = parseInt(data.team3 || 0);
        teamCounts.E = parseInt(data.team4 || 0);
        teamCounts.F = parseInt(data.team5 || 0);
        teamCounts.G = parseInt(data.team6 || 0);
      } else {
        showToast(res.msg);
      }
    })
    .catch((err) => {
      loadingStats.value = false;
      console.error("err", err);
    });
}

// 获取团队成员列表
function getTeamMembers() {
  if (loading.value) return;

  loading.value = true;

  // 转换团队级别为API需要的数字类型
  const levelMap = { B: "1", C: "2", D: "3", E: "4", F: "5", G: "6" };

  // 转换状态为API需要的格式
  const isall = activeStatus.value === "valid" ? "1" : "0";

  getMyTeam({
    page: currentPage.value.toString(),
    limit: pageSize.toString(),
    type: levelMap[activeLevel.value] as any,
    isall: isall,
  })
    .then((res: any) => {
      loading.value = false;

      if (res.code === 200) {
        // API返回的数据结构：res.data是数组
        const members = res.data || [];
        countTeam.value = res.count;
        if (activeStatus.value === "valid") {
          if (currentPage.value === 1) {
            teamMembers.value = members;
          } else {
            teamMembers.value = [...teamMembers.value, ...members];
          }
        } else {
          if (currentPage.value === 1) {
            invalidMembers.value = members.map((item: any) => ({
              phone: `${item.areacode || ""} ${item.tel || ""}`,
              date: item.regTime || "",
              totalDeposit: `COP${item.totalIn || "0"}`,
              maxProductPrice: `COP${item.maxAmouont || "0"}`,
              expiryDate: item.validTime || "-",
            }));
          } else {
            invalidMembers.value = [
              ...invalidMembers.value,
              ...members.map((item: any) => ({
                phone: `${item.areacode || ""} ${item.tel || ""}`,
                date: item.regTime || "",
                totalDeposit: `COP${item.totalIn || "0"}`,
                maxProductPrice: `COP${item.maxAmouont || "0"}`,
                expiryDate: item.validTime || "-",
              })),
            ];
          }
        }

        // 检查是否有更多数据
        hasMore.value = members.length >= pageSize;
      } else {
        showToast(res.msg);
      }
    })
    .catch((err) => {
      loading.value = false;
      console.error("err", err);
    });
}

// 生命周期钩子
onMounted(() => {
  const info = localStorage.getItem("user");
  if (info) {
    try {
      userInfo.value = JSON.parse(info);
    } catch (e) {
      console.error("e", e);
    }
  }

  // 获取团队统计数据
  getTeamStatistics();

  // 获取团队成员数据
  getTeamMembers();
});

// 监听切换团队级别
function switchLevel(level: string) {
  activeLevel.value = level;
  currentPage.value = 1; // 重置页码
  getTeamMembers();
}

// 监听切换状态
function switchStatus(status: string) {
  activeStatus.value = status;
  currentPage.value = 1; // 重置页码
  getTeamMembers();
}

// 加载更多
function loadMore() {
  if (hasMore.value && !loading.value) {
    currentPage.value++;
    getTeamMembers();
  }
}
</script>

<style scoped>
.team-page {
  min-height: 100vh;
  overflow: hidden;
  padding: 0 0 0 0;
  font-size: 17px;
  color: #f6eade;
  background: url("@/assets/images/login/topBg.png") no-repeat top;
  background-size: 100% auto;
}

/* 统计卡片样式 */
.team-stats-card {
  margin: 17px;
  margin-bottom: 43px;
  border: 1px solid rgba(153, 153, 153, 0.2);
  border-radius: 9px;
  overflow: hidden;
  padding: 17px;
}

.stats-row {
  display: flex;
  justify-content: space-between;
}

.stats-left {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  font-size: 13px;
  font-weight: 700;
  color: hsla(0, 0%, 100%, 0.6);
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  height: 56px;
  padding: 5px 0;
}

.stats-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  height: 56px;
  font-weight: 700;
  color: #f6eade;
  font-size: 14px;
  padding: 5px 0;
}

.stats-label {
}

.stats-label-sec {
  font-size: 14px;
  color: rgba(246, 234, 222, 0.7);
}

.stats-value {
  font-size: 16px;
  color: #f6eade;
  font-weight: 700;
}

.divider {
  height: 1px;
  margin-top: 14px;
  margin-bottom: 17px;
  border-top: 1px dashed #726b67;
}

.deposit-row {
  margin-top: 8px;

  padding: 0 10px;
}

.deposit-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.deposit-value {
  font-size: 15px;
  color: #f6eade;
  font-weight: 500;
  margin-bottom: 4px;
}

.deposit-label {
  font-size: 13px;
  font-weight: 700;
  color: hsla(0, 0%, 100%, 0.6);
}

/* 标签容器 */
.tabs-container {
  margin: 15px 15px 0;
  border-radius: 6px 6px 0 0;
  overflow: hidden;
}

/* 团队等级标签样式 */
.team-level-tabs {
  display: flex;
  margin: 0;
  padding: 0 15px;
  background: transparent;
  overflow: hidden;
}

.level-tab {
  flex: 0 0 auto;
  text-align: center;
  padding: 12px 0;
  position: relative;
  margin-right: 20px;
  color: rgba(246, 234, 222, 0.6);
  font-size: 15px;
}

.level-tab.active {
  font-size: 15px;
  color: rgb(246, 234, 222);
  font-weight: bold;
}

.level-underline {
  position: absolute;
  bottom: 0;
  left: 0;
  margin-left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 2px;
  background: #f6eade;
}

/* 状态标签样式 */
.status-tabs {
  display: flex;
  margin: 0;
  padding: 0 20px;
  background: rgba(38, 32, 27, 0.8);
  border-radius: 10px 10px 0 0;
  overflow: hidden;
  border-top: 1px solid #3c3530;
  margin-top: 10px;
}

.status-tab {
  flex: 0 0 auto;
  text-align: center;
  padding: 12px 0;
  font-size: 14px;
  color: rgba(246, 234, 222, 0.7);
  position: relative;
  margin-right: 20px;
}

.status-tab.active {
  color: #f6eade;
  font-weight: 500;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 0;
  margin-left: 50%;
  transform: translateX(-50%);
  width: 15px;
  height: 2px;
  background: #f6eade;
}

/* 内容区域调整 */
.team-content {
  margin: 0 15px 15px;
  min-height: 400px;
  background: rgba(38, 32, 27, 0.8);
  border-radius: 0 0 10px 10px;
}

.member-list {
  padding: 15px;
}

/* 无效成员卡片 */
.invalid-members {
  padding: 0 17px;
}

.invalid-member-card {
  background-color: rgba(34, 26, 21, 0.9);
  border-radius: 8px;
  margin-bottom: 15px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.member-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 5px;
}

.member-phone {
  font-size: 16px;
  font-weight: bold;
  color: #f6eade;
}

.member-date {
  font-size: 12px;
  color: rgba(246, 234, 222, 0.6);
}

.member-info {
  padding: 5px 0;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.info-label {
  font-size: 14px;
  color: rgba(246, 234, 222, 0.6);
}

.info-value {
  font-size: 14px;
  color: #f6eade;
  font-weight: 500;
}

/* 有效成员卡片样式 与无效成员相同 */
.valid-member-card {
  background-color: rgba(34, 26, 21, 0.9);
  border-radius: 8px;
  margin-bottom: 15px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 加载更多样式 */
.load-more-container {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.load-more-btn {
  padding: 10px 20px;
  background: rgba(246, 234, 222, 0.15);
  border-radius: 20px;
  color: #f6eade;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s;
}

.load-more-btn:hover {
  background: rgba(246, 234, 222, 0.25);
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #f6eade;
  font-size: 14px;
}
</style>
